package com.octopus.optiworks.controller;

import org.apache.shiro.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import com.octopus.optiworks.model.Employee;

import java.util.regex.Pattern;

public class UserValidator extends CommonValidator {

    private static final String SIMPLE_EMAIL_REGEX = "[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";

	@Override
    public boolean supports(Class<?> aClass) {
        return Employee.class.isAssignableFrom(aClass);
    }

	@Override
    public void validate(Object o, Errors errors) {
        Employee user = (Employee)o;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.username.empty", "Please specify a username.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email.empty", "Please specify an email address.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "serial", "error.serial.empty", "Please specify a serial.");
        if( StringUtils.hasText( user.getEmail() ) && !Pattern.matches( SIMPLE_EMAIL_REGEX, user.getEmail().toUpperCase() ) ) {
            errors.rejectValue( "email", "error.email.invalid", "Please enter a valid email address." );
        }
        if(user.getId() == null)
        	ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "error.password.empty", "Please specify a password.");
    	//Length invalid
        if(!stepValided)
        	return;
	    if(user.getTestLightCode() != null && user.getTestLightCode().trim().length() > 0 && user.getTestLightCode().trim().length() != 20)
	    	errors.rejectValue( "testLightCode", "error.user.length.invalid.testLightCode", "Please specify Test Light Code with 20 chars." );
    }
}
